#include "Downloader.h"

#include "Data/User.h"

#include <QNetworkRequest>
#include <Network/NetworkAccessManager.h>
namespace TC
{
	namespace Request
	{
		Q_INVOKABLE void Downloader::download(const QUrl &url)
		{
			if (status() == Status::Communicating)
				return;

			thread_local Network::NetworkAccessManager networkAccessManager;
			reply = networkAccessManager.get(QNetworkRequest(url));

			QObject::connect(reply, &QNetworkReply::finished, this, &Downloader::onFinished);
			QObject::connect(reply, &QNetworkReply::downloadProgress, this, &Downloader::onDownloadProgress);

			// error handling
			QObject::connect(
				reply,
				static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
				this,
				&Downloader::autoSetHttpError);

			// auto-delete
			QObject::connect(reply, &QNetworkReply::finished, reply, &QNetworkReply::deleteLater);
			setCommunicationing();
		}


		Q_INVOKABLE void Downloader::abort()
		{
			if (status() != Status::Communicating)
				return;
			if(reply)
			{
				QObject::disconnect(reply);
				reply->abort();
				reply->deleteLater();
				reply = nullptr;
			}
			setReady();
		}

		bool Downloader::isOk()
		{
			if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200)
			{
				qWarning().noquote() << QString("Download finished but failed (%1:%2) : \n%3")
					.arg(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt())
					.arg(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())
					.arg(QString::fromUtf8(reply->readAll()));
			}
			return reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200;
		}
		void Downloader::onFinished()
		{
			if (isOk())
			{
				data = reply->readAll();
				setOk();
			}
			else
				setFailed();
		}

		void Downloader::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
		{
			Downloader::setProgress((double)bytesReceived / bytesTotal);
		}

		QString Downloader::text()
		{
			return QString::fromUtf8(data);
		}

	}
}

